<template>
  <div>
    <canvas id="myCanvas"
            @click="changeVeri"></canvas>
  </div>
</template>
<script>
import { getVeriApi } from '../../api/login'
export default {
  name: "veri",
  data () {
    return {
      veri: ""
    }
  },
  created () {
    this.getVeri();
  },
  methods: {
    changeVeri () { //点击切换验证码
      this.getVeri();
    },
    async getVeri () {
      var res = await getVeriApi()
      console.log(res)
      this.draw(res.data) //调用绘制验证码方法
    },
    randomColor () {
      var r = Math.floor(Math.random() * 256)
      var g = Math.floor(Math.random() * 256)
      var b = Math.floor(Math.random() * 256)
      return "rgb(" + r + "," + g + "," + b + ")"
    },
    draw (aCode) { //aCode 需要传递的4位验证码 ‘AB3C’
      var canvas_width = document.getElementById("myCanvas").offsetWidth; //获取canvans 宽
      var canvas_height = document.getElementById("myCanvas").offsetHeight;//获取canvans 高
      console.log(canvas_width)
      console.log(canvas_height)
      var canvas = document.getElementById("myCanvas");
      var context = canvas.getContext("2d");
      canvas.width = canvas_width;
      canvas.height = canvas_height;
      for (var i = 0; i < 4; i++) {
        var deg = Math.random() - 0.5;//产生一个随机弧度
        var txt = aCode[i]//得到一个字母
        var x = 10 + i * 20;//文字在canvas的x轴坐标
        var y = 20 + Math.random() * 6// 文字在canvas的y轴坐标
        context.font = "bold 23px 微软雅黑";  //准备文字的大小和类型
        context.translate(x, y); // 文字的位置设置
        context.rotate(deg)  //让文字渲染弧度
        context.fillStyle = this.randomColor();//给文字赋值随机颜色
        context.fillText(txt, 0, 0) //开始绘制文字
        context.translate(-x, -y); // 文字的位置设置
        context.rotate(-deg)  //让文字渲染弧度
      }
      // 绘制干扰点
      for (let i = 0; i <= 30; i++) {
        context.strokeStyle = this.randomColor();//随机点的颜色
        context.beginPath();
        let x = Math.random() * canvas_width;
        let y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1)
        context.stroke();
      }
      // 绘制干扰线
      for (let i = 0; i <= 5; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height)
        context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height)
        context.stroke();
      }
    }
  },
}
</script>
<style lang="less" scoped>
canvas {
  width: 135px;
  height: 40px;
  background: white;
  margin-left: 20px;
}
</style>